// /services/AuthService.ts

import http from '@ohos.net.http';
import { ServiceResult, AuthData } from '../models/AuthModels';
import UserSessionManager from '../common/UserSession';
import {AppConfig} from '../common/config'
import dataPreferences from '@ohos.data.preferences';
import ContextManager from '../common/ContextManager';
import hilog from '@ohos.hilog';

const DOMAIN = 0xFF00;
const TAG = 'AuthService';

class AuthService {

  private readonly BASE_URL = AppConfig.API_BASE_URL;

  /**
   * 发送注册请求
   */
  async register(username: string, password: string): Promise<ServiceResult<AuthData>> {
    const url = `${this.BASE_URL}/api/user/register/`;
    hilog.info(DOMAIN, TAG, `发送注册请求到: ${url}`);

    const httpRequest = http.createHttp();
    try {
      const requestBody = { username: username, password };
      hilog.info(DOMAIN, TAG, `注册请求体: ${JSON.stringify(requestBody)}`);

      const response = await httpRequest.request(url, {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify(requestBody)
      });

      hilog.info(DOMAIN, TAG, `注册响应码: ${response.responseCode}`);
      hilog.info(DOMAIN, TAG, `注册响应内容: ${response.result}`);

      if (response.responseCode === 200) {
        const result: ServiceResult<AuthData> = JSON.parse(response.result as string);

        // 注册成功后，检查是否返回了 token
        if (result.code === 200) {
          // 如果后端返回了 token，直接保存
          if (result.data && result.data.token) {
            hilog.info(DOMAIN, TAG, `注册成功，后端返回了token，保存用户会话: username=${result.data.username}`);
            UserSessionManager.login(result.data.username, result.data.token);
            await this.updateUserPreferences(result.data.username, true);
          } else {
            // 如果后端没有返回 token，自动调用登录接口获取 token
            hilog.info(DOMAIN, TAG, `注册成功，但后端未返回token，自动调用登录接口获取token`);
            const loginResult = await this.login(username, password);

            if (loginResult.code === 200 && loginResult.data && loginResult.data.token) {
              hilog.info(DOMAIN, TAG, `自动登录成功，已保存token`);
              // login 方法内部已经调用了 UserSessionManager.login，这里不需要重复调用

              // 更新注册结果，添加 token 信息
              result.data = loginResult.data;
            } else {
              hilog.warn(DOMAIN, TAG, `自动登录失败: ${loginResult.message}`);
            }
          }
        }

        return result;
      } else {
        // HTTP 错误
        hilog.error(DOMAIN, TAG, `注册失败，HTTP状态码: ${response.responseCode}`);
        return {
          code: response.responseCode,
          message: `请求失败 (HTTP ${response.responseCode})`,
          data: null
        } as ServiceResult<AuthData>;
      }
    } catch (error) {
      hilog.error(DOMAIN, TAG, `注册请求失败: ${JSON.stringify(error)}`);
      return {
        code: -1,
        message: '网络请求失败，请检查网络连接',
        data: null
      } as ServiceResult<AuthData>;
    } finally {
      httpRequest.destroy();
    }
  }

  /**
   * 发送登录请求
   * 成功后，http 模块会自动处理并存储 sessionid cookie
   */
  async login(username: string, password: string): Promise<ServiceResult<AuthData>> {
    const url = `${this.BASE_URL}/api/user/login/`;
    hilog.info(DOMAIN, TAG, `发送登录请求到: ${url}`);

    const httpRequest = http.createHttp();
    try {
      const response = await httpRequest.request(url, {
        method: http.RequestMethod.POST,
        header: { 'Content-Type': 'application/json' },
        extraData: JSON.stringify({ username, password })
      });

      hilog.info(DOMAIN, TAG, `登录响应码: ${response.responseCode}`);

      if (response.responseCode === 200) {
        const result: ServiceResult<AuthData> = JSON.parse(response.result as string);

        if (result.code === 200 && result.data && result.data.token) {
          // 登录成功，更新全局会话状态
          UserSessionManager.login(result.data.username, result.data.token);

          // 同时更新preferences以便卡片服务能够访问
          await this.updateUserPreferences(result.data.username, true);
        }
        return result;
      } else {
        // HTTP 错误
        hilog.error(DOMAIN, TAG, `登录失败，HTTP状态码: ${response.responseCode}`);
        return {
          code: response.responseCode,
          message: `请求失败 (HTTP ${response.responseCode})`,
          data: null
        } as ServiceResult<AuthData>;
      }
    } catch (error) {
      hilog.error(DOMAIN, TAG, `登录请求失败: ${JSON.stringify(error)}`);
      return {
        code: -1,
        message: '网络请求失败，请检查网络连接',
        data: null
      } as ServiceResult<AuthData>;
    } finally {
      httpRequest.destroy();
    }
  }

  /**
   * 更新用户preferences数据
   */
  private async updateUserPreferences(username: string, isLogin: boolean): Promise<void> {
    try {
      // 从ContextManager获取上下文
      const context = ContextManager.getContext();
      
      const pref = await dataPreferences.getPreferences(context, 'user_info');
      await pref.put('isLogin', isLogin);
      await pref.put('userName', username);
      await pref.flush();
      
      hilog.info(DOMAIN, TAG, `已更新preferences: isLogin=${isLogin}, userName=${username}`);
    } catch (error) {
      hilog.error(DOMAIN, TAG, `更新preferences失败: ${JSON.stringify(error)}`);
    }
  }

  /**
   * 发送退出登录请求
   * http 模块会自动携带已保存的 cookie
   */
  async logout(): Promise<ServiceResult<null>> {
    const url = `${this.BASE_URL}/api/user/logout/`;
    hilog.info(DOMAIN, TAG, `发送登出请求到: ${url}`);

    const httpRequest = http.createHttp();
    try {
      const response = await httpRequest.request(url, {
        method: http.RequestMethod.POST
      });

      hilog.info(DOMAIN, TAG, `登出响应码: ${response.responseCode}`);

      if (response.responseCode === 200) {
        const result: ServiceResult<null> = JSON.parse(response.result as string);

        if (result.code === 200) {
          // 登出成功，清除全局会话状态
          UserSessionManager.logout();

          // 同时更新preferences
          await this.updateUserPreferences('', false);
        }
        return result;
      } else {
        // HTTP 错误
        hilog.error(DOMAIN, TAG, `登出失败，HTTP状态码: ${response.responseCode}`);
        return {
          code: response.responseCode,
          message: `请求失败 (HTTP ${response.responseCode})`,
          data: null
        } as ServiceResult<null>;
      }
    } catch (error) {
      hilog.error(DOMAIN, TAG, `登出请求失败: ${JSON.stringify(error)}`);
      return {
        code: -1,
        message: '网络请求失败，请检查网络连接',
        data: null
      } as ServiceResult<null>;
    } finally {
      httpRequest.destroy();
    }
  }
}

// 导出一个单例，方便在UI层直接使用
export const authService = new AuthService();